var sharedData = require("dataMgr");
var helper = require("Helpers");
//游戏核心逻辑处理脚本
cc.Class({
    extends: cc.Component,

    properties: {
        role: {
            default: null,
            type: cc.Node
        },
        gameLayer: {
            default: null,
            type: cc.Node
        },
        //开始层
        startlayer: {
            default: null,
            type: cc.Node
        },
        gameOverLayer:{
            default: null,
            type: cc.Node
        },
        //升级按钮
        updateBnt: {
            default: null,
            type: cc.Node
        },
        shareBnt: {
            default: null,
            type: cc.Node
        },
        movieBnt: {
            default: null,
            type: cc.Node
        },
        //道具层
        proplayer: {
            default: null,
            type: cc.Node
        },
        //弹出层
        dialoglayer: {
            default: null,
            type: cc.Node
        },
        //子弹层
        bulletslayer: {
            default: null,
            type: cc.Node
        },
        //cell层
        cellslayer: {
            default: null,
            type: cc.Node
        },
        //子弹预制
        butPrefab: {
            default: null,
            type: cc.Prefab
        },
        //子弹打击效果预制
        butPtPrefab: {
            default: null,
            type: cc.Prefab
        },
        //模块爆破特效
        cellPtPrefab: {
            default: null,
            type: cc.Prefab
        },
        //单局最高分数
        topScoreLabel: {
            default: null,
            type: cc.Label
        },
        //单局最高分数
        lastScoreLabel: {
            default: null,
            type: cc.Label
        },
        //总共有多少金币
        allGoldLabel: {
            default: null,
            type: cc.Label
        },
        //看视频加多少金币
        vedioGoldLabel: {
            default: null,
            type: cc.Label
        },
        clickStartGame:{
            default: null,
            type: cc.Node
        },
        //发射子弹的速度
        roleSpeedLabel: {
            default: null,
            type: cc.Label
        },
        //单颗子弹的攻击力
        rolePowerLabel: {
            default: null,
            type: cc.Label
        },
        //游戏的分数
        scoreLabel: {
            default: null,
            type: cc.Label
        },
        //当前的道具预制
        speedPropPrefab: {
            default: null,
            type: cc.Prefab
        },
        //当前的道具预制
        powerPropPrefab: {
            default: null,
            type: cc.Prefab
        },
        //当前的道具预制
        multPropPrefab: {
            default: null,
            type: cc.Prefab
        },
        //负责播放音效的类
        audioNode:{
            default: null,
            type: cc.Node
        }
    },

    soundHelper:function(){
        return this.audioNode.getComponent("soundplay");
    },

    resetRoleInfo: function () {
        this.topScoreLabel.string = "最高分数："+helper.getKNum(sharedData.maxScore);
        this.lastScoreLabel.string="上局分数："+helper.getKNum(sharedData.lastScore);
        this.allGoldLabel.string=helper.getKNum(sharedData.roleGold);
        this.vedioGoldLabel.string="+"+helper.getKNum(sharedData.games.vedioAddGold);
        this.roleSpeedLabel.string = sharedData.curRoleSpeedInfo.speed.toString();
        this.rolePowerLabel.string = sharedData.curRolePowerInfo.power.toString();
    },

    restartGame: function (isRestart) {
        this._startGame = false;
        this._butpassTime = 0;//控制子弹的时间间隔
        this._emypassTime = 0;//控制子弹的时间间隔
        this._curDelay = sharedData.games.cellDelay;
        this._curCount = 0;//当前出了几波模块
        this._score = 0;
        this.gameLayer.active=false;
        this.scoreLabel.node.active = false;
        this.scoreLabel.string = "0";
        //获取一开始需要开几波模块
        this._firstCount = helper.getRandomInt(sharedData.games.firstTimes.minTimes, sharedData.games.firstTimes.maxTimes);
        this.resetRoleInfo();

        if (isRestart) {
            this.bulletslayer.removeAllChildren(true);
            this.cellslayer.removeAllChildren(true);
            this.proplayer.removeAllChildren(true);
            this.role.getComponent("role").resetRole();
            this.startlayer.active = true;
            this.startlayer.runAction(cc.fadeIn(0.2));
        }
    },

    resumeGame:function(){
        this._curCount = 0;//当前出了几波模块
        this.resetRoleInfo();
        this.bulletslayer.removeAllChildren(true);
        this.cellslayer.removeAllChildren(true);
        this.proplayer.removeAllChildren(true);
        this.role.getComponent("role").resetRole();
    },

    addScores: function (score) {
        if (!this.role.active) {
            return;
        }
        this._score += score;
        this.scoreLabel.string = helper.getKNum(this._score);
        this.scoreLabel.node.runAction(cc.sequence(cc.scaleTo(0.1, 1.2, 1.2), cc.scaleTo(0.1, 1, 1)));
    },
    getDiffc: function () {
        let add = parseInt(this._curCount * sharedData.games.addRatio);
        //获取当前最小的系数
        this._minNumRadio = sharedData.games.minRatio + add;
        //获取当前最大的系数
        this._maxNumRadio = sharedData.games.maxRatio + add;
        //获取当前的随机模块概率
        this._randNum = sharedData.games.randNum.slice(0);
        let addperc = parseInt(this._curCount * sharedData.games.change1Sec);
        let sum = 0;
        for (let i = 0; i < sharedData.games.randNum; i++) {
            sum += sharedData.games.randNum[i];
            if (addperc <= sum) {
                this._randNum[i] = sum;
                break;
            } else if (i == sharedData.games.randNum.length - 1) {
                this._randNum[i] = sum;
            } else {
                this._randNum[i] = 0;
            }
        }
    },

    dealRoleMove: function () {
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (e) {
            if (typeof (this._startGame) == 'undefined' || !this.role.active) {
                return;
            }
            if(!this._startGame)return;
            let move_x = e.getLocation().x - e.getPreviousLocation().x;
            if ((move_x < 0 && this.role.tag == 2) || (move_x > 0 && this.role.tag == 3)) {
                //如果是碰撞了还操作，直接返回不移动英雄
                return;
            }
            let tmpX = 0;
            let roleX = this.role.x;
            if (roleX + move_x < -this.node.width / 2 + this.role.width / 2) {
                tmpX = -this.node.width / 2 + this.role.width / 2;
            } else if (roleX + move_x > this.node.width / 2 - this.role.width / 2) {
                tmpX = this.node.width / 2 - this.role.width / 2;
            } else {
                tmpX = roleX + move_x;
            }
            this.role.position = cc.p(tmpX, this.role.y);
        }.bind(this), this);
    },

    createRoleBullets: function (dt) {
        if (!this.role.active) {
            return;
        }
        this._butpassTime += dt;
        let speed = sharedData.curRoleSpeedInfo.speed;
        let roleInfo = this.role.getComponent("role");
        if (roleInfo.isInPropSpeed) {
            //处于加速状态
            speed = speed * sharedData.speedProp.speedTimes;
        }
        let time = 1 / speed;
        if (this._butpassTime >= time) {
            this._butpassTime = 0;

            //这里来继续调用
            let power = sharedData.curRolePowerInfo.power;
            if (roleInfo.isInPropPower) {
                //处于增加力量状态
                power = power * sharedData.powerProp.powerTimes;
            }
            if (roleInfo.isInPropMult) {
                //多条弹道状态
                this.createBullet(this.role.x, -sharedData.multButProp.angleDev, sharedData.games.bulletMoveSpeed, power, roleInfo.isInPropPower);
                this.createBullet(this.role.x, sharedData.multButProp.angleDev, sharedData.games.bulletMoveSpeed, power, roleInfo.isInPropPower);
            }
            let initX = this.role.x;
            let sendxs = dt / time;
            if (sendxs > 1) {
                //速度太快已无法单独发射，就在能量上面弥补
                this.createBullet(initX, 0, sharedData.games.bulletMoveSpeed, parseInt(power * sendxs), roleInfo.isInPropPower);
            } else {
                this.createBullet(initX, 0, sharedData.games.bulletMoveSpeed, power, roleInfo.isInPropPower);
            }
        }
    },

    //速度特别快的时候，可以使用两条弹道
    createBullet: function (initX, angle, speed, power, isPowerUp) {
        let bullet = null;
        if (this._bulletPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            bullet = this._bulletPool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            bullet = cc.instantiate(this.butPrefab);
        }
        if (isPowerUp) {
            bullet.scale = 1.3;
        } else {
            bullet.scale = 1;
        }
        bullet.parent = this.bulletslayer; // 将生成的敌人加入节点树
        let initY = this.role.y + this.role.height / 2 * this.role.scale;
        bullet.getComponent("bullet").initData(cc.p(initX, initY), angle, speed, power);
    },

    removeBullet: function (bullet) {
        let tmp = cc.instantiate(this.butPtPrefab);
        tmp.position = bullet.position;
        this.gameLayer.addChild(tmp);
        this._bulletPool.put(bullet);
    },

    bulletMove: function (dt) {
        for (let i = 0; i < this.bulletslayer.childrenCount; i++) {
            var but = this.bulletslayer.children[i];
            let isOutScreen = but.getComponent("bullet").move(this._rect, dt);
            if (isOutScreen) {
                this._bulletPool.put(but);
                i--;
            }
        }
    },
    createCurEnemy: function () {
        this._curCount++;
        this.getDiffc();//先获取难度系数
        //再进行出兵选择
        var name;
        if (this._curCount < this._firstCount) {
            //开始出初始的几波模块
            let emys = sharedData.games.firstTimes.enemys;//这是个数组
            let index = helper.getRandomInt(0, emys.length - 1);
            //取出对应的模块
            let info = sharedData.enemyGroups[emys[index] - 1];
            name = info.filename;
        } else {
            if (this._curCount == this._firstCount) {
                //这里还需要把英雄以及cell层里面已有的元素进行缩放
                this.role.runAction(cc.scaleTo(0.5, 0.8, 0.8));
                for (let i = 0; i < this.cellslayer.childrenCount; i++) {
                    this.cellslayer.children[i].runAction(cc.scaleTo(0.5, 0.8, 0.8));
                }
            }
            //随机一个1到100的值，看看随机到了哪个模型
            let rand = helper.getRandomInt(1, 100);
            let sum = 0;
            let curIndex = this._randNum.length - 1;
            for (let i = 0; i < this._randNum.length; i++) {
                sum += this._randNum[i];
                if (rand <= sum) {
                    curIndex = i;
                    break;
                }
            }
            let emyId = sharedData.games.randEnemys[curIndex];
            let info = sharedData.enemyGroups[emyId - 1];
            name = info.filename;
        }
        //这里是创建，里面包含了创建时间
        cc.loader.loadRes(name, cc.Prefab, function (error, data) {
            if (error) {
                cc.log(error);
            } else {
                let roleValue = sharedData.curRolePowerInfo.power * sharedData.curRoleSpeedInfo.speed;
                let minV = parseInt(roleValue * this._minNumRadio);
                let maxV = parseInt(roleValue * this._maxNumRadio);
                var emy;
                if (cc.supportJit) {
                    cc.supportJit = false;
                    emy = cc.instantiate(data);
                    cc.supportJit = true;
                }
                else {
                    // 如果是特殊的不支持 JIT 的平台，则不需要优化，也不能强制设置 cc.supportJit 为 true
                    emy = cc.instantiate(data);
                }
                //let emy = cc.instantiate(data);
                //前15波有一半的概率出现比较容易过去的地方
                let easy = helper.isRandPercent(50) && this._curCount <= 15;
                emy.getComponent("base").initData(cc.p(0, this.node.height / 2 + emy.height / 2),
                    sharedData.games.cellMoveSpeed, this._rect, minV, maxV,
                    helper.isRandPercent(sharedData.games.cellStarPercent), easy, this);
                this.cellslayer.addChild(emy);

                //如果出现随机道具的话
                if (helper.isRandPercent(sharedData.speedProp.rand)) {
                    //如果出现速度道具
                    this.createProp(0, emy.height);
                } else if (helper.isRandPercent(sharedData.powerProp.rand)) {
                    //如果出现增强道具
                    this.createProp(1, emy.height);
                } else if (helper.isRandPercent(sharedData.multButProp.rand)) {
                    //如果出现三条线路的道具
                    this.createProp(2, emy.height);
                }
                //给时间重新进行一个赋值操作
                this._emypassTime = 0;
                this._curDelay = sharedData.games.cellDelay + emy.height / sharedData.games.cellMoveSpeed;
            }
        }.bind(this));

    },

    createProp: function (type, cellHeight) {
        let prop = null;
        if (type == 0) {
            prop = cc.instantiate(this.speedPropPrefab);
        } else if (type == 1) {
            prop = cc.instantiate(this.powerPropPrefab);
        } else if (type == 2) {
            prop = cc.instantiate(this.multPropPrefab);
        }
        let randX = helper.getRandomInt(parseInt(prop.width - this.node.width / 2), parseInt(this.node.width / 2 - prop.width));
        let randY = helper.getRandomInt(parseInt(prop.height), parseInt(prop.height + 500));
        prop.position = cc.p(randX, this.node.height / 2 + cellHeight + randY);
        prop.getComponent("prop").initData(this,sharedData.games.cellMoveSpeed, this._rect);
        this.proplayer.addChild(prop);
    },

    removeAllCells: function () {
        for (let i = 0; i < this.cellslayer.childrenCount; i++) {
            let cell = this.cellslayer.children[i];
            cell.getComponent("base").removeAllCells();
        }
    },

    removeCell: function (cell, color) {
        let tmp = cc.instantiate(this.cellPtPrefab);
        let pat = tmp.getComponent(cc.ParticleSystem);
        pat.startColor = color;
        pat.endColor = color;
        let point = cell.convertToWorldSpaceAR(cc.p(0, -cell.height / 2));
        tmp.position = this.gameLayer.convertToNodeSpaceAR(point);
        this.gameLayer.addChild(tmp);
        //先销毁cell
        cell.destroy();
        //这里播放一个爆破的声音
        this.soundHelper().playBroken();
    },

    //重置英雄的位置,左边还是右边
    resetRolePos: function (cell, left) {
        let point = cell.convertToWorldSpaceAR(cc.p(0, 0));
        if (left) {
            point = cc.p(point.x - this.node.width / 2 + cell.width / 2, point.y - this.node.height / 2);
            this.role.position = cc.p(point.x + this.role.width / 2 - 2, this.role.y);
        } else {
            point = cc.p(point.x - this.node.width / 2 - cell.width / 2, point.y - this.node.height / 2);
            this.role.position = cc.p(point.x - this.role.width / 2 + 2, this.role.y);
        }
    },

    checkDie: function (cell) {
        let rect = cell.getBoundingBoxToWorld();
        let rect1 = this.role.getBoundingBoxToWorld();
        if (Math.abs(rect1.yMax - rect.yMin) <= 20) {
            this.gameOver();
            this.soundHelper().playDead();
        }
    },

    gameOver: function () {
        this.role.active = false;
        let tmp = cc.instantiate(this.cellPtPrefab);
        let pat = tmp.getComponent(cc.ParticleSystem);
        pat.startColor = this.role.color;
        pat.endColor = this.role.color;
        tmp.position = this.role.position;
        this.gameLayer.addChild(tmp);

        this.gameOverLayer.getComponent("gameover").startShow(this,this._score);
        //this.dialoglayer.getComponent("dialog").createFinishDialog(this._score, this);
    },
    //看视频和分享
    seeMovie:function(){
        this._wxad = wx.createRewardedVideoAd({ adUnitId: 'xxxx' });
        this._wxad.show();
    },

    share:function(){
        wx.shareAppMessage({
            title: '方块射击',
            imageUrl: canvas.toTempFilePathSync({
                destWidth: 500,
                destHeight: 400
              })
          });
    },

    // use this for initialization
    onLoad: function () {
        //开启碰撞检测
        cc.director.getCollisionManager().enabled = true;
        //cc.director.getCollisionManager().enabledDebugDraw = true;
        //cc.director.getCollisionManager().enabledDrawBoundingBox = true;
        //创建子弹的对象池
        this._rect = this.node.getBoundingBoxToWorld();
        this._bulletPool = new cc.NodePool();
        sharedData.initData(function () {
            this.restartGame(false);
        }.bind(this));

        this.updateBnt.getComponent("button")._callback = function () {
            //点击升级按钮后执行操作
            this.dialoglayer.getComponent("dialog").createUpdateDialog(this);
        }.bind(this);

        this.shareBnt.getComponent("button")._callback = function () {
            //点击分享按钮后执行操作
            this.share();
        }.bind(this);

        this.movieBnt.getComponent("button")._callback = function () {
            //点击看视频按钮后执行操作
            
        }.bind(this);

        this.clickStartGame.on(cc.Node.EventType.TOUCH_START, function (e) {
            if (!this._startGame) {
                this.gameLayer.active=true;
                this._startGame = true;
                this.scoreLabel.node.active = true;
                this.scoreLabel.node.scale = 0;
                this.scoreLabel.node.runAction(cc.sequence(cc.delayTime(0.3), cc.scaleTo(0.2, 1, 1)));
                this.startlayer.runAction(cc.sequence(
                    cc.fadeOut(0.2), cc.callFunc(function () {
                        this.startlayer.active = false;
                    }, this)));
            }
        }.bind(this), this);
    },

    start: function () {
        //开始方法
        this.dealRoleMove();
    },
    // called every frame
    update: function (dt) {
        if (this._startGame) {
            //子弹移动处理
            this.bulletMove(dt);
            //间隔时间出子弹
            this.createRoleBullets(dt);
            //以下是处理出模块的逻辑
            this._emypassTime += dt;
            if (this._emypassTime >= this._curDelay) {
                this._emypassTime = 0;
                this.createCurEnemy();
            }
        }
    },
    // lateUpdate() {
    //     let context = cc.sys.__audioSupport.context;
    //     if (context.state === 'suspended') {
    //         context.resume();
    //         console.log(context.state);
    //     }
    // }
});